# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$config)

maxRuns <- configJson$maxRun %>%
  as.numeric()
pValue <- configJson$pValue %>%
  as.numeric()

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- opt$i
if (!file.exists(fileName)) {
  quit(status = 0)
}

data <- read_tsv(opt$i) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  column_to_rownames("SampleID") %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame()

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

borutaRs <- Boruta(x, y, maxRuns = maxRuns, pValue = pValue)

statData <- attStats(borutaRs) %>%
  rownames_to_column("Metabolite")
outData <- statData %>%
  arrange(desc(medianImp)) %>%
  column_to_rownames("Metabolite")
outFileName <- paste0(parent, "/Decision_Info.csv")
write.csv(outData, outFileName)
save(borutaRs, file = "boruta.RData")










